package demo.gui;

import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class ListFiles {
	private Frame main;
	private Button but;
	private TextField tf;
	private TextArea ta;
	private Dialog d;
	private Button ok;
	private Label lab;

	public ListFiles() {
		init();
	}

	private void init() {
		main = new Frame("�г��ļ�");
		but = new Button("ת��");
		tf = new TextField(30);
		ta = new TextArea(23, 40);
		main.setBounds(600, 300, 320, 450);
		main.setLayout(new FlowLayout());
		main.add(tf);
		main.add(but);
		main.add(ta);
		myEvebt();
		main.setVisible(true);
	}

	private void myEvebt() {
		main.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		but.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				trigger();
			}
		});
		tf.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER)
					trigger();
			}
		});
	}

	public void trigger() {
		ta.setText("");
		File f = new File(tf.getText());
		if (f.exists() && f.isDirectory()) {
			print(f, 0);
		} else {
			tf.setText("");
			dialog();
		}
	}

	private void dialog() {
		d = new Dialog(main, "��ʾ", true);
		d.setBounds(650, 350, 300, 200);
		d.setLayout(new FlowLayout());
		lab = new Label("û���ҵ�" + tf.getText() + "������������");
		ok = new Button("ȷ��");
		d.add(lab);
		d.add(ok);
		d.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				d.setVisible(false);
			}
		});
		ok.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				d.setVisible(false);
			}
		});
		ok.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				int i = e.getKeyCode();
				if ((i == KeyEvent.VK_ENTER) || i == KeyEvent.VK_ESCAPE) {
					d.setVisible(false);
				}
			}
		});
		d.setVisible(true);
	}

	public void print(File dir, int level) {
		File[] files = dir.listFiles();
		level++;
		ta.append(getLevel(level) + dir.getName() + "\n");
		for (File file : files) {
			if (file.isDirectory()) {
				print(file, level);
				continue;
			}
			ta.append(getLevel(level + 1) + file.getName() + "\n");
		}
	}

	public String getLevel(int level) {
		StringBuilder sb = new StringBuilder();
		sb.append("|��");
		for (int i = 0; i < level; i++) {
			sb.insert(0, "  ");
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		new ListFiles();
	}

}
